<template>
  <div class="progress-box">
    <!-- <el-tabs
      type="border-card"
      class="tabs-border-box"
      @tab-change="handleChangeTab"
      v-model="state.tabActive"
    >
      <el-tab-pane
        v-for="(item, index) in state.tabsTitleArr"
        :key="index"
        :label="`${item.modelName}-${item.disTypeName}`"
        :name="item.scid"
      > -->
    <div class="key-value">
      <div class="title">
        <span>当前计算进度</span>
      </div>
      <div class="title-key">
        <el-progress
          class="progress"
          color="#96F300"
          :text-inside="true"
          :stroke-width="20"
          :percentage="state.progressArr[0]?.scProgress"
          status="success"
        />
      </div>
      <div class="title-time">
        <span>开始时间:</span>
        <i>{{ state.progressArr[0]?.calcStart || '--' }}</i>
        <span>结束时间:</span>
        <i>{{ state.progressArr[0]?.calcEnd || '--' }}</i>
      </div>
    </div>
    <div class="collapse-box">
      <el-collapse
        v-model="state.activeName"
        :key="index"
        v-for="(item, index) in state.progressArr[0]?.zoneInfos"
      >
        <el-collapse-item :name="index + 1">
          <template #title>
            <div class="coll-title">
              <div class="ip-img">
                <img src="@/assets/images/dispatch/u38.png" />
              </div>
              <div class="ip-word">
                <span>资源分区:</span>
              </div>
              <div class="ip-num">
                <span>{{ item.zoneName }}</span>
              </div>
              <!-- <div class="ip-status">
                          <span>正常</span>
                        </div>-->
              <div class="ip-icon">
                <i :class="iconActive(index + 1) ? 'downArrow2' : 'downArrow1'"></i>
              </div>
            </div>
          </template>
          <div class="collapse-main">
            <div class="main-box">
              <div
                class="main-item"
                :key="childIndx"
                v-for="(childItem, childIndx) in item.groupInfos"
              >
                <div class="item-title">
                  <div class="title-icon">
                    <img src="@/assets/images/dispatch/u39.png" />
                  </div>
                  <div class="title-name">
                    <span>计算组：</span>
                  </div>
                  <div class="title-word">
                    <el-tooltip :content="childItem.groupName" placement="top">
                      <span>{{ childItem.groupName }}</span>
                    </el-tooltip>
                  </div>
                  <div class="title-ip">
                    <el-tooltip :content="childItem.host" placement="top">
                      <span>{{ childItem.host }}</span>
                    </el-tooltip>
                  </div>
                  <div class="progress-box">
                    <el-progress
                      class="progress"
                      color="#96F300"
                      :text-inside="true"
                      :stroke-width="20"
                      :percentage="childItem.progress"
                      status="success"
                    />
                  </div>
                </div>
                <div class="item-detail">
                  <div class="ul-box">
                    <div class="li-box" :key="num" v-for="(e, num) in childItem.secInfos">
                      <div class="li-item">
                        <div class="li-icon">
                          <img src="@/assets/images/dispatch/u40.png" />
                        </div>
                        <div class="li-name">
                          <span>
                            {{ `${e.blknm} 水文:${e.chlModel || '--'}` }}
                            {{ e.resvModel ? '水库:' + e.resvModel : '' }}
                          </span>
                        </div>
                      </div>
                      <div class="li-status">
                        <div class="status-icon">
                          <img src="@/assets/images/dispatch/u28.png" v-if="e.status == 0" />
                          <img src="@/assets/images/dispatch/u44.png" v-if="e.status == 4" />
                          <img src="@/assets/images/dispatch/u54.png" v-else-if="e.status == 1" />
                          <img src="@/assets/images/dispatch/u60.png" v-else-if="e.status == 2" />
                          <img src="@/assets/images/dispatch/u62.png" v-else-if="e.status == 3" />
                          <img
                            src="@/assets/images/dispatch/waring.png"
                            v-else-if="e.status == 5"
                          />
                        </div>
                        <div class="status-name">
                          <span v-if="e.status == 0">未启动</span>
                          <span v-else-if="e.status == 1">等待中</span>
                          <span v-else-if="e.status == 2">水文计算中</span>
                          <span v-else-if="e.status == 3">水库调度中</span>
                          <span v-else-if="e.status == 4">已完成</span>
                          <span v-else-if="e.status == 5">异&nbsp;&nbsp;&nbsp;常</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <!-- </el-tab-pane>
    </el-tabs> -->
  </div>
</template>

<script setup>
import { ref, reactive, watch, onBeforeUnmount, defineExpose, onUnmounted } from 'vue'
import {
  // 查询方案详情
  getDispatchSchemeDetail,
  getComputSchemeProgress,
  getDispatchStatusValue,
  getDispatchManualSchemeProgSectionExtent
} from '@/services/modules/dispatch-manage.js'
import { BASE_URL } from '@/services/config'
import emitter from '@/utils/bus'
import { IMG_LAYER } from '@/constants'
import { addImageToMap, removeLayer, clearLayer } from '@/utils/mapUtils'

const state = reactive({
  layerMapLoading: false,
  scid: '',
  timer: null,
  statusTimer: null,
  fourAngle: '',
  progressItem: '',
  tabActive: '',
  progressArr: [],

  activeName: ['1', '2'],
  //
  tabsTitleArr: [],
  progressTimer: null,
  getStatusInerVal: null,
  computedStatus: ''
})

const props = defineProps({
  map: {
    type: Object,
    default: {}
  },
  scid: {
    type: String,
    default: ''
  }
})
const emit = defineEmits('refreshScheme')
onUnmounted(() => {
  clearTime()
})
// 获取四角值
function getFourAngle(id) {
  return new Promise((resolve, reject) => {
    getDispatchManualSchemeProgSectionExtent({ scid: id }).then((res) => {
      if (res.code === 200) {
        console.log(res)
        state.fourAngle = {
          xmax: res.data.xmax,
          ymax: res.data.ymax,
          xmin: res.data.xmin,
          ymin: res.data.ymin
        }
        resolve(state.fourAngle)
      }
    })
  })
}

onBeforeUnmount(() => {
  clearTime()
})
const iconActive = (data) => {
  return state.activeName.includes(data)
}
// 动态加载地图
function getDispatchStatus(id) {
  // state.progressArr.scProgress ='0.0'
  // removeLayer(mapInstance,IMG_LAYER)
  console.log(state.layerMapLoading, '地图')
  if (state.layerMapLoading) {
    addImageToMap(
      props.map,
      IMG_LAYER,
      BASE_URL + '/map/vectorTiles/getDispatchManualSchemeProgSection',
      state.fourAngle.xmin,
      state.fourAngle.ymin,
      state.fourAngle.xmax,
      state.fourAngle.ymax,
      id
    )
  }
}
//状态接口轮训
function getByForEachChildStatus(id) {
  clearInterval(state.getStatusInerVal)
  state.getStatusInerVal = ''
  state.getStatusInerVal = setInterval(async () => {
    await getChildComputedStatus(id)
    if (state.computedStatus == 2 || state.computedStatus == 0) {
      clearInterval(state.getStatusInerVal) // 终止循环
      state.getStatusInerVal = ''
      emit('refreshScheme')
    }
    emit('refreshScheme')
  }, 3000)
}
//进度接口循环查询
function forEachGetProgress(id) {
  clearInterval(state.progressTimer)
  state.progressTimer = null
  state.progressTimer = setInterval(async () => {
    // 刷新列表
    await getChildProgress(id)
    getDispatchStatus(id)
    // if (state.computedStatus !==1) {
    if (state.progressArr[0]?.scProgress == '100.0' || state.computedStatus == 0) {
      //当计算完成 则关闭计算循环
      clearInterval(state.progressTimer)
      state.progressTimer = null
    }
  }, 3000)
  //             // removeLayer(mapInstance, IMG_LAYER)
}
// 子方案计算进度
function getChildProgress(scid) {
  return new Promise((resolve, reject) => {
    getComputSchemeProgress({ scid }).then((res) => {
      if (res.code === 200) {
        state.progressArr = [res.data]
        resolve(state.progressArr)
      }
    })
  })
}
// 获取子方案计算状态
function getChildComputedStatus(id) {
  return new Promise((resolve, reject) => {
    getDispatchStatusValue({
      scid: id
      // fcid: state.scCode
    }).then((res) => {
      if (res.code === 200) {
        state.computedStatus = res.data[0].status
        console.log(state.computedStatus, '计算状态1')
        resolve(state.computedStatus)
      }
    })
  })
}
// 查询方案详情
// function acceptSchemeDetail(id) {
//   state.tabsTitleArr = []
//   state.progressArr = []
//   // scBelong:（0：洪水预报，1：调度预报）
//   getDispatchSchemeDetail({ scid: id, scBelong: 0 }).then(async (res) => {
//     if (res.code == 200) {
//       state.tabsTitleArr = res.data.models.info
//       if (state.tabsTitleArr.length) {
//         for (let index = 0; index < state.tabsTitleArr.length; index++) {
//           let item = state.tabsTitleArr[index]
//           await getComputSchemeProgress({ scid: item.scid }).then((res) => {
//             if (res.code === 200) {
//               state.progressItem = res.data
//             }
//           })
//           state.progressArr.push(state.progressItem)
//         }

//         // handleChangeTab(state.tabsTitleArr[0].scid)
//         console.log('123', state.progressArr)
//       }
//     }
//   })
// }
// 获取子方案id，查询计算状态，对应四角值，并且获取计算进度，渲染地图，如果状态为计算中则进入循环获取计算状态和计算进度，并持续渲染地图
async function getChildIdComputed(scid) {
  console.log(scid, '计算状态2')
  removeLayer(mapInstance, IMG_LAYER)
  clearTime()
  // 查询计算进度轮训
  forEachGetProgress(scid)
  //状态
  getByForEachChildStatus(scid)
  await getChildProgress(scid)
  await getChildComputedStatus(scid)

  // 获取四角值
  await getFourAngle(scid)
  // 动态加载地图
  await getDispatchStatus(scid)
  console.log(state.computedStatus, '计算状态')
  if (state.computedStatus == 1) {
    // 查询计算进度轮训
    forEachGetProgress(scid)
    //状态
    getByForEachChildStatus(scid)
  } else {
    clearTime()
  }
}
function whetherLoadingMap(name) {
  if (name == 'third') {
    state.layerMapLoading = true
    getChildIdComputed(props.scid)
  } else {
    // 点击其它则不加载。去除图层
    state.layerMapLoading = false
    removeLayer(mapInstance, IMG_LAYER)
  }
}
function clearTime() {
  clearInterval(state.getStatusInerVal)
  clearInterval(state.progressTimer)
}
defineExpose({
  getChildIdComputed,
  whetherLoadingMap,
  clearTime
})
</script>

<style lang="less" scoped>
.progress-box {
  height: 100%;
  :deep(.tabs-border-box) {
    height: 95%;
    :deep(.el-tabs__header) {
      margin: 0;
      .el-tabs__item {
        padding: 0 30px;
        font-size: 20px;
        font-weight: 500;
      }
    }
  }
}

.key-value {
  display: flex;
  line-height: 35px;
  font-size: 14px;
  .title {
    margin-right: 25px;
    span {
      color: #797979;
    }
  }
  .title-key {
    :deep(.el-progress-bar__outer) {
      border: 1px solid #96f300;
    }
    .progress {
      width: 250px;
    }
    display: flex;
    justify-content: center;
    align-items: center;
    span {
      color: #0154db;
    }
  }
  .title-time {
    // margin-left: 20px;
    display: flex;
    align-items: center;
    i {
      color: #797979;
      margin-left: 15px;
    }
    span {
      margin-left: 10px;
    }
  }
}
.collapse-box {
  padding: 15px;
  overflow-y: auto;
  height: 80%;
  .el-collapse {
    .el-collapse-item {
      // height: 30px;
      // :deep(.el-collapse-item__header) {
      //   // height: 30px;
      // }
      :deep(.el-collapse-item__arrow) {
        display: none;
      }
      // :deep(.el-collapse-item__header) {
      //   justify-content: space-between;
      // }
      .coll-title {
        display: flex;
        position: relative;
        width: 100%;
        .ip-img {
          display: flex;
          justify-content: center;
          align-items: center;
          margin-right: 5px;
          img {
            width: 20px;
            height: 20px;
          }
        }
        .ip-word {
          margin-right: 5px;
          span {
            color: #797979;
          }
        }
        .ip-num {
          margin-right: 200px;
          span {
            color: black;
            font-weight: 600;
          }
        }
        .ip-status {
          span {
            color: #81be3a;
          }
        }
        .ip-icon {
          display: flex;
          justify-content: center;
          align-items: center;
          position: absolute;
          right: 10px;
          top: 15px;
          cursor: pointer;
          .downArrow1 {
            display: inline-block;
            width: 20px;
            height: 20px;
            background-image: url(@/assets/images/dispatch/u61.png);
            background-repeat: no-repeat;
            background-size: 100% 100%;
          }
          .downArrow2 {
            display: inline-block;
            width: 20px;
            height: 20px;
            transform: rotate(-180deg);
            background-image: url(@/assets/images/dispatch/u61.png);
            background-repeat: no-repeat;
            background-size: 100% 100%;
          }
        }
      }
      .collapse-main {
        height: 100%;
        .main-box {
          .main-item {
            margin-top: 5px;
            .item-title {
              display: flex;
              .title-icon {
                margin-right: 2px;
                margin-left: 20px;
                img {
                  width: 20px;
                  height: 20px;
                }
              }
              .title-name {
                margin-right: 15px;
                span {
                  color: #797979;
                  font-size: 12px;
                }
              }
              .progress-box {
                width: 150px;
                margin-left: 50px;
              }
              .title-word {
                width: 120px;
                span {
                  display: inline-block;
                  width: 120px;
                  overflow: hidden;
                  white-space: nowrap;
                  text-overflow: ellipsis;
                  color: #0054db;
                  font-size: 12px;
                  cursor: pointer;
                }
              }
              .title-ip {
                width: 120px;
                span {
                  display: inline-block;
                  width: 120px;
                  color: black;
                  font-size: 12px;
                  overflow: hidden;
                  white-space: nowrap;
                  text-overflow: ellipsis;
                  cursor: pointer;
                }
              }
            }
            .item-detail {
              height: 100%;
              .ul-box {
                max-height: 200px;
                overflow-y: auto;
                .li-box {
                  display: flex;
                  justify-content: space-between;
                  margin: 15px 0 0 50px;
                  .li-item {
                    display: flex;
                    font-size: 12px;
                    .li-icon {
                      margin-right: 5px;
                      img {
                        width: 20px;
                        height: 20px;
                      }
                    }
                    .li-name {
                      span {
                        color: black;
                      }
                    }
                  }
                  .li-status {
                    display: flex;
                    margin-right: 100px;
                    .status-icon {
                      margin-right: 5px;
                      img {
                        width: 20px;
                        height: 20px;
                      }
                    }
                    .status-name {
                      span {
                        color: black;
                        font-size: 12px;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
